package com.aisino.mvpdesignproject2.http.uitl;

import com.aisino.mvpdesignproject2.constant.AppConstants;
import com.aisino.mvpdesignproject2.http.api.ApiService;
import com.aisino.mvpdesignproject2.http.itf.Stateful;
import com.aisino.mvpdesignproject2.http.rxjava.BaseObserver;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @author 1
 * @date 2018/8/30
 */

public class HttpUtils {

    public static <T> void invoke(Stateful stateful, Observable<T> observable, BaseObserver<T> callback) {
//        Stateful target = null;
        callback.setTarget(stateful);

        /**
         * 先判断网络连接状态和网络是否可用，放在回调那里好呢，还是放这里每次请求都去判断下网络是否可用好呢？
         * 如果放在请求前面太耗时了，如果放回掉提示的速度慢，要10秒钟请求超时后才提示。
         * 最后采取的方法是判断网络是否连接放在外面，网络是否可用放在回掉。
         */
        if (!NetworkUtils.isConnected()) {
            ToastUtils.showShort("网络连接已断开");
            if (stateful != null) {
                stateful.setState(AppConstants.STATE_ERROR);
            }
            return;
        }

        RetrofitManager.getManager()
                .getRetrofit()
                .create(ApiService.class)
                .getNewsList("")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(callback);

//        Subscription subscription = observable.subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(callback);
//        lifecycle.bindSubscription(subscription);

    }
}
